//
//  putUpViewController.swift
//  NewLndd
//
//  Created by 邵禹曦 on 2020/1/6.
//  Copyright © 2020 辽宁当代. All rights reserved.
//

import UIKit
import SwiftyJSON

// MARK: - 挂单买入，卖出
class putUpViewController: HomeApiViewController {
    
    // MARK: - 属性
    
    @IBOutlet weak var con: UILabel!
    @IBOutlet weak var coi: UITextField!
    @IBOutlet weak var m3j1: UILabel!   // 买1买价
    @IBOutlet weak var m3l1: UILabel!   // 买1买量
    @IBOutlet weak var m3j2: UILabel!   // 买2买价
    @IBOutlet weak var m3l2: UILabel!   // 买2买量
    @IBOutlet weak var m3j3: UILabel!   // 买3买价
    @IBOutlet weak var m3l3: UILabel!   // 买3买量
    
    
    @IBOutlet weak var m4j1: UILabel!   // 卖1买价
    @IBOutlet weak var m4l1: UILabel!   // 买1买量
    @IBOutlet weak var m4j2: UILabel!   // 卖2买价
    @IBOutlet weak var m4l2: UILabel!   // 买2买量
    @IBOutlet weak var m4j3: UILabel!   // 卖3买价
    @IBOutlet weak var m4l3: UILabel!   // 买3买量
    
    @IBOutlet weak var LAST: UILabel!   // 最新
    @IBOutlet weak var HIGH: UILabel!   // 最高
    @IBOutlet weak var LOW: UILabel!    // 最低
    
    
    
    
    
    @IBOutlet weak var mrBtn: DLRadioButton!    // 买入按钮
    @IBOutlet weak var mcBtn: DLRadioButton!    // 卖出按钮
    @IBOutlet weak var tj: UIButton!                // 提交按钮
    @IBOutlet weak var jg:  UITextField! // 买入价 txt
    @IBOutlet weak var sl:  UITextField!// 买入数量 txt
    @IBOutlet weak var mrjg: UILabel!   // 买入价
    @IBOutlet weak var mrsl: UILabel!   // 买入数量
    
    @IBOutlet weak var BtnSegmentClick: UISegmentedControl!
    @IBOutlet weak var chhz: UIView!
    @IBOutlet weak var BtncjhzC: UIView!
    @IBOutlet weak var BtngdC: UIView!
    @IBOutlet weak var BtnzzC: UIView!
    
    var put = putUpView()
    // 获取下拉coi
    var _coi : String = ""
    var mm : String = "1" // 买：1 卖：2
    
    override func viewDidLoad() {
        super.viewDidLoad()
        showInfo()
    }
    
    // MARK: - 绑定4个UISegmentedControl按钮
    @IBAction func cs(_ sender: UISegmentedControl) {
        switch BtnSegmentClick.selectedSegmentIndex {
        case 0:
            chhz.isHidden = false
            BtncjhzC.isHidden = true
            BtngdC.isHidden = true
            BtnzzC.isHidden = true
        case 1:
            chhz.isHidden = true
            BtncjhzC.isHidden = false
            BtngdC.isHidden = true
            BtnzzC.isHidden = true
        case 2:
            chhz.isHidden = true
            BtncjhzC.isHidden = true
            BtngdC.isHidden = false
            BtnzzC.isHidden = true
        case 3:
            chhz.isHidden = true
            BtncjhzC.isHidden = true
            BtngdC.isHidden = true
            BtnzzC.isHidden = false
        default:
            break;
        }
    }
    
}

// MARK: - 用户验证
extension putUpViewController {
    private func showInfo() {
        // GCD
        let group = DispatchGroup()
 
        // 从沙盒中获取参数
         var userPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
         userPath =  (userPath as NSString).appendingPathComponent("data.plist")
         user = NSKeyedUnarchiver.unarchiveObject(withFile: userPath) as? User
        
        Thread.sleep(forTimeInterval: 0.05)


        // 用户验证
        self.u = user?.U!
        self.retcode = user?.RETCODE!
        // 用户验证
        let str = [u,"101",retcode]
         
        //self.isLogin = self._network(str: str as! [String], group: group)
        group.enter()
        NetworkTools.share.check_user(code: str as Array<Any>) { (result, error) in
                      
                          if error != nil {
                              print("no no no")
                              return
                          }
                          

                          if Int(self._retcode(res: result!))! < 0 {
                              self.isLogin = false
                          } else {
                              self.isLogin = true
                          }
                          group.leave()
                      }

        group.notify(queue: DispatchQueue.main) {
            if !self.isLogin {
                return self.setupVisitorView()
            } else {
                Thread.sleep(forTimeInterval: 0.05)
                // 2.设置导航栏内容
                self.setupNavigationBar()
                self.showTabBtn()
                self.ShouInfo()
            }
         }
    }
}



// MARK: - 设置UI界面
extension putUpViewController {
    private func setupNavigationBar() {
        
   
        mrBtn.addTarget(self, action: #selector(mrBtnClick), for: .touchUpInside)
        mcBtn.addTarget(self, action: #selector(mcBtnClick), for: .touchUpInside)
        tj.addTarget(self, action: #selector(tjBtnClick), for: .touchUpInside)
        //BtnSegmentClick.addTarget(self, action: #selector(SegBtnClick), for: .touchUpInside)

    }
    
    @objc private func mrBtnClick() {
        mrjg.text = "买入价:"
        mrsl.text = "买入数量:"
        self.mm = "1"
    }
    @objc private func mcBtnClick() {
        mrjg.text = "卖出价:"
        mrsl.text = "卖出数量:"
        self.mm = "2"
    }


    // MARK: - 测试用
    @objc @IBAction private func logSelectedButton(radioButton : DLRadioButton) {
        if (radioButton.isMultipleSelectionEnabled) {
            for button in radioButton.selectedButtons() {
                print(String(format: "%@ is selected.\n", button.titleLabel!.text!));
            }
        } else {
            print(String(format: "%@ is selected.\n", radioButton.selected()!.titleLabel!.text!));
        }
    }
    
    
    // 按钮控制tableView
    @objc private func showTabBtn() {
        chhz.isHidden = false
        BtncjhzC.isHidden = true
        BtngdC.isHidden = true
        BtnzzC.isHidden = true
    }
    
    @objc private func SegBtnClick() {
        
    }

}


// MARK: - 买入/卖出 展示信息
extension putUpViewController {
    // 显示数据默认第一条
    @objc private func ShouInfo() {
        // 获取coi
        //_coi = coi.text!
        let str = [user?.U!,user?.RETCODE! , _coi]
        NetworkTools.share.commodity_data_query(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            
            //print(resultArray)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) < 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "数据加载失败")
                            return self.setupVisitorView()
                        }
                    }
                }
            }
            
            
            
            let rstJson = JSON(resultArray)
            self.coi.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["COI"].stringValue )
            self.con.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["CON"].stringValue )
            self.LAST.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["LAST"].stringValue )
            self.HIGH.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["HIGH"].stringValue )
            self.LOW.text = (rstJson["REP"]["RESULTLIST"]["REC"][0]["LOW"].stringValue )
            
            self.m3j1.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][0]["BP"].stringValue
            self.m3l1.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][0]["BQ"].stringValue
            self.m4j1.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][0]["SP"].stringValue
            self.m4l1.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][0]["SQ"].stringValue
            
            self.m3j2.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][1]["BP"].stringValue
            self.m3l2.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][1]["BQ"].stringValue
            self.m4j2.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][1]["SP"].stringValue
            self.m4l2.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][1]["SQ"].stringValue
            
            self.m3j3.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][2]["BP"].stringValue
            self.m3l3.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][2]["BQ"].stringValue
            self.m4j3.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][2]["SP"].stringValue
            self.m4l3.text = rstJson["REP"]["RESULTLIST"]["REC"][0]["BSL"]["BS"][2]["SQ"].stringValue
            
            
            self.coi.addTarget(self, action: #selector(self.selectDate(_:)), for: .touchDown)
        }
            
    }
    
    @objc func selectDate(_ btn: UITextField) {
        //print(self.psdm.text)
        self.performSegue(withIdentifier: "gdxl", sender: self.coi.text)
        //self.pickerView.isHidden = false
        
        //self.pickerView.removeFromSuperview()

    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // 买挂单
        if segue.identifier == "gdxl" {
            let secVC = segue.destination as! putPickerViewController
            //if let IndexPath = sender as? putUpView {
            secVC._comInfo?.COI = sender as? String
            //}
        }
        
     
    }

}


// MARK: - 入委托单
extension putUpViewController {
    
    
    @objc private func tjBtnClick() {
        guard self.jg.text != "" else {
            if #available(iOS 13.0, *) {
                self.showMsgbox(_message: "价格不能为空")
            }
            return
        }
        
        guard self.sl.text != "" else {
            if #available(iOS 13.0, *) {
                self.showMsgbox(_message: "数量不能为空")
            }
            return
        }
        
        let str = [user?.U!,user?.RETCODE! ,"", _coi,"" ,self.jg.text!, self.mm,"1",self.sl.text!]
        NetworkTools.share.loadorder(code: str as Array<Any>) { (result, error) in
            
            if error != nil {
                print("no no no")
                return
            }
            

            
            // 获取可选类型中的数组
            guard let resultArray = result else {
                print("no")
                return
            }
            
            
            print(resultArray)
            if let REP = resultArray["REP"] as? [String : AnyObject] {
                if let arr = REP["RESULT"] as? [String : AnyObject]   {
                    let code : Int = Int(arr["RETCODE"] as! String)!
                    if(Int(truncating: NSNumber(value: code)) > 0) {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "请求成功")
                        }
                    } else {
                        if #available(iOS 13.0, *) {
                            self.showMsgbox(_message: "请求失败")
                        }
                    }
                }
            }
        
        }
    }
}
